#include<iostream>
#include<unistd.h>
#include<cstring>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cout << "./udpcliant serverip serverport" << std::endl;
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cout << "socket create error" << std::endl;
        exit(1);
    }
    
    struct sockaddr_in server;
    memset(&server,0,sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(1)
    {
        std::cout << "Please input# ";
        std::string line;
        getline(std::cin,line);

        int n = sendto(sockfd,line.c_str(),line.size(),0,(struct sockaddr*)&server,sizeof(server));
        if(n > 0)
        {
            char buffer[1024];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            int m = recvfrom(sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&tmp,&len);
            if(m > 0)
            {
                std::cout << buffer << std::endl;
            }
        }
    }

    return 0;
}